﻿using OpenAiClient.Events;
using OpenAiClient.Services;
using OpenAiClient.Tools;
using OpenAiClient.Util.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;

namespace OpenAiClient.ViewModels
{
    internal class FeedbackViewModel : BindableBase
    {
        public DelegateCommand CommitCmd { get; }

        public string Name
        {
            get => _name;
            set => SetProperty(ref _name, value);
        }

        public string Content
        {
            get => _content;
            set => SetProperty(ref _content, value);
        }

        private string _name = string.Empty;
        private string _content = string.Empty;

        private readonly ILogService _logService;
        private readonly IConfigService _configService;
        private readonly IHttpService _httpService;
        private readonly IEventAggregator _eventAggregator;

        public FeedbackViewModel(
            ILogService logService,
            IConfigService configService,
            IHttpService httpService,
            IEventAggregator eventAggregator
        )
        {
            _logService = logService;
            _configService = configService;
            _httpService = httpService;
            _eventAggregator = eventAggregator;
            CommitCmd = new DelegateCommand(OnCommitAsync);
        }

        private async void OnCommitAsync()
        {
            var content = Content.Trim();
            if (string.IsNullOrWhiteSpace(content))
            {
                _eventAggregator.GetEvent<ShowGrowlWarningEvent>().Publish("请输入留言内容");
                return;
            }

            if (string.IsNullOrWhiteSpace(_configService.AccountId))
            {
                var text = $@"请求服务器失败(Error code = {Constants.ErrorNotRegister})";
                _eventAggregator.GetEvent<ShowGrowlWarningEvent>().Publish(text);
                return;
            }

            var dto = new
            {
                // ReSharper disable once RedundantAnonymousTypePropertyName
                AccountId = _configService.AccountId,
                Name = Name.Trim(),
                Content = content
            };
            var body = JsonHelper.SerializeObject(dto);
            var url = $"{_configService.WebApiUrl}/api/statistics/feedback/pc";
            var ret = await _httpService.PostAsync(url, body);
            if (!ret.Item1)
            {
                var message = $"向服务器提交留言失败：{ret.Item2}.";
                _eventAggregator.GetEvent<ShowGrowlWarningEvent>().Publish(message);
                _logService.Error(message);
            }
            else
            {
                Name = string.Empty;
                Content = string.Empty;
                _eventAggregator.GetEvent<ShowGrowlSuccessEvent>().Publish("留言成功");
            }
        }
    }
}
